package hr.web.portlet.portal.liferay;

import hr.web.portlet.util.jsf.JSFPortletUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.portlet.PortletSession;

/**
 * 
 * @author ivica
 */
public class PortalPage {

	private static final String CURRRENT_PAGE = "CURRENT_PAGE";
	private static final String PAGES = "/pages.properties";

	private static final Properties pages = new java.util.Properties();
	static {
		try {
			pages.load(Thread.currentThread().getContextClassLoader()
					.getResourceAsStream(PAGES));
		} catch (IOException ex) {
			throw new RuntimeException(ex);
		}
	}

	private String page;
	private Map<String, Object> parameters = new HashMap<String, Object>();

	private PortalPage(String page) {
		this.page = page;
	}

	public static PortalPage currentPage() {
		return (PortalPage) JSFPortletUtil.getPortletSession().getAttribute(
				CURRRENT_PAGE, PortletSession.APPLICATION_SCOPE);
	}

	public static PortalPage newPage(String page) {
		PortalPage pp = (PortalPage) JSFPortletUtil.getPortletSession()
				.getAttribute(CURRRENT_PAGE, PortletSession.APPLICATION_SCOPE);
		if (pp != null) {
			pp.parameters.clear();
		}

		pp = new PortalPage(page);
		JSFPortletUtil.getPortletSession().setAttribute(CURRRENT_PAGE, pp,
				PortletSession.APPLICATION_SCOPE);
		return pp;
	}

	public void redirect() {
		JSFPortletUtil.sendRedirect(pages.getProperty(page));
	}

	public PortalPage addParameter(String name, Object value) {
		parameters.put(name, value);
		return this;
	}

	public Object getParameter(String name) {
		return parameters.get(name);
	}
}
